const { items, connectDB } = require('../public/javascripts/utils');
const item = items(__filename);
// // 连接数据库
// connectDB();
class ItemService {
  async create(itemData) {
    try {
      return await item.create(itemData);
    } catch (error) {
      throw error;
    }
  }

  async update(id, itemData) {
    console.log(id, itemData)
    const para = {
      title_cn: itemData.title_cn,
      desc: itemData.desc,
      updateuser: itemData.updateUser,
      updateTime: Date.now()
    }
    const where = { '_id': id };
    try {
      return await item.findOneAndUpdate(where, para); 
    } catch (error) {
      throw error;
    }
  }

  async findById(id) {
    try {
      return await item.findById(id);
    } catch (error) {
      throw error;
    }
  }

  async find(para) {
    console.log("传递过来的参数",para)
    try {
      return await item.findOne(para).select('+password');
    } catch (error) {
      throw error;
    }
  }

  async findAll(ctx) {
    console.log("传递过来的参数",ctx)
    const substring = ctx.title_cn
    let para = {}
    if(substring) { // 如果传了title_cn
      para.title_cn =  { $regex: substring }
    } 
    if(substring == null) {
      delete para.title_cn
    }
    try {
      const pageIndex = parseInt(ctx.pageIndex) || 1
      const pageSize = parseInt(ctx.pageSize) || 10
      const total = await item.countDocuments(para)
      const res = await item.find(para).skip(pageSize * (pageIndex - 1)).limit(pageSize)
      return {res, total}
    } catch (error) {
      throw error;
    }
  }

  async delete(id) {
    try {
      return await item.findByIdAndDelete(id);
    } catch (error) {
      throw error;
    }
  }
}

module.exports = new ItemService();